package com.hiss.basic.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.hiss.basic.client.system.ISysRoleMenuService;
import com.hiss.basic.model.system.domain.SysRoleMenuDomain;
import com.hiss.basic.model.system.request.SysRoleMenuUpdateRequest;
import com.hiss.basic.starter.core.helper.ValidationHelper;
import com.hiss.basic.system.mapper.SysRoleMenuMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 系统角色菜单 service impl
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenuDomain> implements ISysRoleMenuService {

    @Override
    public List<SysRoleMenuDomain> findList(Collection<Long> roleIds) {
        if (CollectionUtil.isNotEmpty(roleIds)) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.in(SysRoleMenuDomain::getRoleId, roleIds);
            return list(wrapper);
        }
        return ListUtil.toList();
    }

    @Override
    public void create(SysRoleMenuUpdateRequest request) {
        ValidationHelper.validate(request);

        List<SysRoleMenuDomain> roleMenuList = ListUtil.toList();

        if (CollectionUtil.isNotEmpty(request.getMenuIdList())) {
            Set<Long> menuIdList = request.getMenuIdList();
            for (Long item : menuIdList) {
                SysRoleMenuDomain domain = new SysRoleMenuDomain();
                domain.setRoleId(request.getRoleId());
                domain.setMenuId(item);
                roleMenuList.add(domain);
            }
        }

        Db.tx(() -> {
            removeByRoleId(request.getRoleId());

            if (CollectionUtil.isNotEmpty(roleMenuList)) {
                saveBatch(roleMenuList);
            }
            return Boolean.TRUE;
        });
    }

    @Override
    public void removeByRoleId(Long roleId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(SysRoleMenuDomain::getRoleId, roleId);
        remove(wrapper);
    }
}
